import { useUserStore } from "@/stores/index";
import { useStorage } from '@/utils/storeage';
import system from './system'
import { $page } from "@/utils/index";

let baseURL = system.baseUrl
const RequestHeaders = (options) => {
	const { getToken, isLogin, initUserInfo } = useUserStore();
	initUserInfo()
	const header = {};
	if (isLogin()) {
		header['Authorization'] = getToken();
	}
	if (options.header) {
		Object.assign(headers, options.header);
	}
	header['Appid'] = system.appid()
	header['cid'] = useStorage().get('CATEGORY')
	header['Accept'] = 'application/json, text/plain, */*';
	return header;
}


const request = (options) => {
	return new Promise((resolve, reject) => {
		uni.request({
			...options,
			success: (res) => {
				let data = res.data
				if (data.code == 200) {
					resolve(res.data);
				} else {
					if (data.code == 12000) {
						useUserStore().clearUserInfo()
						$page.switch('/pages/user/user')
						return;
					} else {
						uni.showModal({
							title: '温馨提示',
							content: data.msg
						})
					}
					reject(res);
				}

			},
			fail: (err) => {
				reject(err);
			},
			complete: () => {
				uni.hideLoading()
			}
		})
	})
}

export const $http = {
	baseURL,
	get: (url, data = {}, options = {}) => {
		if (!options) {
			options = {}
		}
		options.header = RequestHeaders(options)
		options.url = `${baseURL}${url}`
		options.data = data
		options.method = 'GET'
		return request(options)
	},
	post: (url, data = {}, options = {}) => {
		if (!options) {
			options = {}
		}
		options.header = RequestHeaders(options)
		options.url = `${baseURL}${url}`
		options.data = data
		options.method = 'POST'
		return request(options)
	},
	custom: (url, method, data = {}, options = {}) => {
		if (!options) {
			options = {}
		}
		options.header = RequestHeaders(options)
		options.url = `${baseURL}${url}`
		options.data = data
		options.method = method
		return request(options)
	},
	upload: (url, options = {}) => {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				formData: {
					is_hide: 1
				},
				...options,
				header: RequestHeaders(options),
				url: `${baseURL}${url}`,
				success: (res) => {
					let data = res.data
					const isString1 = typeof data === 'string';
					if (isString1) {
						data = JSON.parse(data)
					}
					if (data.code == 200) {
						resolve(data);
					} else {
						uni.showModal({
							title: '温馨提示',
							content: data.msg
						})
						reject(res);
					}
				},
				fail: (err) => {
					reject(err);
				},
			})
		})
	}
}